package top.kangyaocoding.ecommerce.impl;

import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.kangyaocoding.ecommerce.IFileService;
import top.kangyaocoding.ecommerce.IMailService;
import top.kangyaocoding.ecommerce.IUsersService;
import top.kangyaocoding.ecommerce.constants.Constants;
import top.kangyaocoding.ecommerce.dao.IUsersDao;
import top.kangyaocoding.ecommerce.dto.UsersDTO;
import top.kangyaocoding.ecommerce.exception.AppException;
import top.kangyaocoding.ecommerce.po.Users;
import top.kangyaocoding.ecommerce.redis.IRedisService;
import top.kangyaocoding.ecommerce.response.Response;
import top.kangyaocoding.ecommerce.utils.AESUtil;
import top.kangyaocoding.ecommerce.utils.JwtUtil;
import top.kangyaocoding.ecommerce.utils.VerificationCodeUtil;
import top.kangyaocoding.ecommerce.vo.UserRoleVO;
import top.kangyaocoding.ecommerce.vo.UserStatusVO;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 用户服务实现类
 *
 * @author K·Herbert
 * @since 2025-02-17 上午11:54
 */
@Slf4j
@Service
public class UsersService implements IUsersService {

    @Resource
    private IUsersDao usersDao;
    @Resource
    private IRedisService redisService;
    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private AESUtil aesUtil;
    @Resource
    private IMailService mailService;

    /**
     * 使用密码登录
     *
     * @param email    用户邮箱
     * @param password 用户密码
     * @return 登录成功返回 JWT 令牌
     */
    @Override
    public Response<String> loginByPassword(String email, String password) {
        if (isEmpty(email) || isEmpty(password)) {
            return Response.<String>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(null).build();
        }
        // 根据邮箱查找用户
        Users users = usersDao.findByEmail(email);
        if (users == null) {
            log.error("密码登录，但用户不存在: {}", Constants.ErrorCode.LOGIN_ERROR.getInfo());
            return Response.<String>builder()
                    .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                    .data(null).build();
        }
        if (users.getUserStatus().equals(UserStatusVO.FROZEN.getCode())) {
            log.error("密码登录，但用户被冻结: {}", Constants.ErrorCode.USER_STATUS_FROZEN.getInfo());
            return Response.<String>builder()
                    .code(Constants.ErrorCode.USER_STATUS_FROZEN.getCode())
                    .info(Constants.ErrorCode.USER_STATUS_FROZEN.getInfo())
                    .data(null).build();
        }
        // 获取加密密码并解密
        String decryptPassword;
        try {
            decryptPassword = aesUtil.decrypt(users.getPassword());
        } catch (Exception e) {
            log.error("密码解密失败: 用户ID：{}, 邮箱：{}", users.getId(), email, e);
            throw new AppException(
                    Constants.ErrorCode.LOGIN_ERROR.getCode(),
                    Constants.ErrorCode.LOGIN_ERROR.getInfo(),
                    e
            );
        }
        // 校验密码是否匹配
        if (!password.equals(decryptPassword)) {
            log.error("密码校验失败，用户：{}", email);
            return Response.<String>builder()
                    .code(Constants.ErrorCode.LOGIN_ERROR.getCode())
                    .info(Constants.ErrorCode.LOGIN_ERROR.getInfo())
                    .data(null).build();
        }
        // 生成 JWT Token
        String role = users.getUserRole();
        Long userId = Long.valueOf(users.getId());
        String token = jwtUtil.generateToken(userId,email, role);
        log.info("使用密码登录成功，email：{}，role：{}，token：[{}]", email, role, token);
        // 返回认证结果
        return Response.<String>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(token).build();
    }

    /**
     * 使用验证码登录
     *
     * @param email            用户邮箱
     * @param verificationCode 验证码
     * @return 登录成功返回 JWT 令牌
     */
    @Override
    public Response<String> loginByVerificationCode(String email, String verificationCode) {
        if (isEmpty(email) || isEmpty(verificationCode)) {
            return Response.<String>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(null)
                    .build();
        }
        Users users = usersDao.findByEmail(email);
        if (users == null) {
            log.error("验证码登录，但用户不存在: {}", Constants.ErrorCode.LOGIN_ERROR.getInfo());
            return Response.<String>builder()
                    .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                    .data(null)
                    .build();
        }
        // 校验验证码
        String key = Constants.VERIFICATION_CODE_KEY + email;
        String cacheCode = redisService.getValue(key);
        if (isEmpty(cacheCode) || !cacheCode.equals(verificationCode)) {
            log.info("验证码不存在或错误，email：{}", email);
            return Response.<String>builder()
                    .code(Constants.ErrorCode.VERIFICATION_CODE_ERROR.getCode())
                    .info(Constants.ErrorCode.VERIFICATION_CODE_ERROR.getInfo())
                    .data(null)
                    .build();
        }
        String role = users.getUserRole();
        Long userId = Long.valueOf(users.getId());
        // 删除验证码
        redisService.remove(key);
        // 生成 JWT Token
        String token = jwtUtil.generateToken(userId,email, role);
        log.info("使用验证码登录成功，email：{}，token：[{}]", email, token);
        // 返回认证结果
        return Response.<String>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(token)
                .build();
    }

    /**
     * 注册新用户
     *
     * @param email            用户邮箱
     * @param password         用户密码
     * @param verificationCode 验证码
     * @return 注册成功返回 true，失败返回 false
     */
    @Override
    public Response<Boolean> register(String email, String password, String verificationCode) {
        if (isEmpty(email) || isEmpty(password) || isEmpty(verificationCode)) {
            log.error("注册参数错误: {}", Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false)
                    .build();
        }
        // 校验用户是否存在
        Users existingUser = usersDao.findByEmail(email);
        if (existingUser != null) {
            log.error("用户已存在: {}", Constants.ErrorCode.USER_EXIST.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.USER_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_EXIST.getInfo())
                    .data(false)
                    .build();
        }
        // 校验验证码
        String key = Constants.VERIFICATION_CODE_KEY + email;
        String cacheCode = redisService.getValue(key);
        if (isEmpty(cacheCode) || !cacheCode.equals(verificationCode)) {
            log.error("验证码不存在或错误，email：{}", email);
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.VERIFICATION_CODE_ERROR.getCode())
                    .info(Constants.ErrorCode.VERIFICATION_CODE_ERROR.getInfo())
                    .data(false)
                    .build();
        }
        // 删除验证码
        redisService.remove(key);
        // 创建用户
        try {
            String encryptPassword = aesUtil.encrypt(password);
            usersDao.save(Users.builder()
                    .email(email)
                    .password(encryptPassword)
                    .nickname(email.substring(0, email.indexOf("@")))
                    .build());
            log.info("新增一位用户：{}", email);
        } catch (Exception e) {
            log.error("注册失败: {}", e.getMessage());
            throw new AppException(
                    Constants.ErrorCode.REGISTER_ERROR.getCode(),
                    Constants.ErrorCode.REGISTER_ERROR.getInfo(),
                    e
            );
        }
        // 返回注册结果
        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(true)
                .build();
    }

    /**
     * 发送验证码到邮箱
     *
     * @param email 用户邮箱
     */
    @Override
    public void sendVerificationCode(String email) {
        if (isEmpty(email)) {
            log.error("发送验证码失败，邮箱为空");
            return;
        }
        String verificationCode = VerificationCodeUtil.generateVerificationCode();
        log.info("生成验证码成功，验证码：{}", verificationCode);
        // 将验证码保存到 Redis
        redisService.setValue(Constants.VERIFICATION_CODE_KEY + email, verificationCode, Constants.VERIFICATION_CODE_EXPIRATION_TIME);
        // 发送验证码到邮箱
        mailService.sendVerificationEmail(email, verificationCode);
    }

    /**
     * 获取用户信息
     *
     * @param token 用户邮箱
     * @return 用户信息
     */
    @Override
    public Response<UsersDTO> getUserInfo(String token) {
        // 从 Token 中获取用户邮箱
        String email = jwtUtil.getEmailFromToken(token);
        // 从 Redis 中获取用户信息
        String key = Constants.USER_INFO_KEY + email;
        String cacheUser = redisService.getValue(key);
        // 如果不存在，从数据库中获取
        if (isEmpty(cacheUser)) {
            Users user = usersDao.findByEmail(email);
            if (user == null) {
                log.error("获取用户信息失败，用户不存在: {}",
                        Constants.ErrorCode.USER_NOT_EXIST.getInfo());
                return Response.<UsersDTO>builder()
                        .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                        .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                        .data(null)
                        .build();
            }
            cacheUser = JSON.toJSONString(user);
            redisService.setValue(key, cacheUser,
                    Constants.USER_INFO_EXPIRATION_TIME);
            log.info("从数据库中获取用户信息并存储到 Redis: {}", email);
        }
        Users users = JSON.parseObject(cacheUser, Users.class);
        // 返回用户信息
        UsersDTO usersDTO = UsersDTO.builder()
                .id(users.getId())
                .email(users.getEmail())
                .nickname(users.getNickname())
                .avatarUrl(users.getAvatarUrl())
                .biography(users.getBiography())
                .userStatus(users.getUserStatus())
                .userRole(users.getUserRole())
                .build();
        log.info("获取用户信息成功: {}", email);
        // 返回用户信息
        return Response.<UsersDTO>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(usersDTO)
                .build();
    }

    /**
     * 更新用户密码
     *
     * @param email            用户邮箱
     * @param verificationCode 验证码
     * @param newPassword      新密码
     * @return 更新结果 true: 更新成功 false: 更新失败
     */
    @Override
    public Response<Boolean> updateUserPassword(String email,
                                                String verificationCode,
                                                String newPassword) {
        if (isEmpty(email) || isEmpty(verificationCode)
                || isEmpty(newPassword)) {
            log.error("密码更新失败，参数错误: {}", Constants.ErrorCode
                    .ILLEGAL_PARAMETER.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false)
                    .build();
        }
        String key = Constants.VERIFICATION_CODE_KEY + email;
        String cacheCode = redisService.getValue(key);
        if (isEmpty(cacheCode) || !cacheCode.equals(verificationCode)) {
            log.error("密码更新失败，验证码不存在或错误: {}", Constants
                    .ErrorCode.VERIFICATION_CODE_ERROR.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.VERIFICATION_CODE_ERROR.getCode())
                    .info(Constants.ErrorCode.VERIFICATION_CODE_ERROR.getInfo())
                    .data(false)
                    .build();
        }
        Users user = usersDao.findByEmail(email);
        if (user == null) {
            log.error("密码更新失败，用户不存在: {}", email);
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                    .data(false)
                    .build();
        }
        try {
            // 加密新密码
            String encryptPassword = aesUtil.encrypt(newPassword);
            // 更新用户密码
            user.setPassword(encryptPassword);
            usersDao.update(user);
            // 删除验证码
            redisService.remove(key);
            log.info("用户：{}，密码更新成功！", email);
        } catch (Exception e) {
            // 记录详细的异常信息
            log.error("更新密码失败: 邮箱：{}", email, e);
            throw new AppException(
                    Constants.ErrorCode.UN_ERROR.getCode(),
                    Constants.ErrorCode.UN_ERROR.getInfo(),
                    e
            );
        }
        // 返回更新结果
        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(true)
                .build();
    }

    @Override
    public Response<String> getUserEmailAndSendVerificationCode(String token) {
        // 从 Token 中获取用户邮箱
        try {
            String email = jwtUtil.getEmailFromToken(token);
            this.sendVerificationCode(email);
            return Response.<String>builder()
                    .code(Constants.ErrorCode.SUCCESS.getCode())
                    .info(Constants.ErrorCode.SUCCESS.getInfo())
                    .data(email)
                    .build();
        } catch (Exception e) {
            log.error("获取用户邮箱失败: {}", Constants.ErrorCode.UN_ERROR.getInfo());
            throw new AppException(
                    Constants.ErrorCode.UN_ERROR.getCode(),
                    Constants.ErrorCode.UN_ERROR.getInfo(),
                    e
            );
        }
    }

    @Resource
    private IFileService fileService;

    @Override
    public Response<Boolean> updateUserAvatar(MultipartFile file, String token) throws IOException {
        if (file == null || file.isEmpty()) {
            log.error("更新用户头像失败，参数错误: {}", Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false)
                    .build();
        }
        // 再判断一下文件大小
        //max-file-size: 2MB
        //max-request-size: 2MB
        if (file.getSize() > 2 * 1024 * 1024) {
            log.error("更新用户头像失败，文件大小超过 2MB");
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.UNSUPPORTED_AVATAR_FILE_SIZE.getCode())
                    .info(Constants.ErrorCode.UNSUPPORTED_AVATAR_FILE_SIZE.getInfo())
                    .data(false)
                    .build();
        }
        // 仅支持 gif,png,jpg,jpeg,webp
        // 获取文件原始名并检查扩展名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            log.error("更新用户头像失败，文件名无效");
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false)
                    .build();
        }
        // 支持的图片格式
        Set<String> allowedExtensions = new HashSet<>(Arrays.asList("gif", "png", "jpg", "jpeg", "webp"));

        // 获取文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

        // 检查文件格式是否支持
        if (!allowedExtensions.contains(extension)) {
            log.error("更新用户头像失败，不支持的文件格式: {}", extension);
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.UNSUPPORTED_AVATAR_FILE_TYPE.getCode())
                    .info(Constants.ErrorCode.UNSUPPORTED_AVATAR_FILE_TYPE.getInfo())
                    .data(false)
                    .build();
        }
        // 获取邮箱
        String email = null;
        try {
            email = jwtUtil.getEmailFromToken(token);
        } catch (Exception e) {
            log.error("获取用户邮箱失败: {}", Constants.ErrorCode.UN_ERROR.getInfo(), e);
            throw new AppException(
                    Constants.ErrorCode.UN_ERROR.getCode(),
                    Constants.ErrorCode.UN_ERROR.getInfo(),
                    e
            );
        }
        Users user = usersDao.findByEmail(email);
        if (user == null) {
            log.error("更新用户头像失败，用户不存在: {}", email);
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                    .data(false)
                    .build();
        }

        Response<String> response = fileService.uploadFile(file);
        if (!response.getCode().equals(Constants.ErrorCode.SUCCESS.getCode())) {
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.UN_ERROR.getCode())
                    .info(Constants.ErrorCode.UN_ERROR.getInfo())
                    .data(false)
                    .build();
        }
        String url = response.getData();
        Users newUser = Users.builder()
                .email(user.getEmail())
                .avatarUrl(url)
                .build();
        // 更新用户信息
        usersDao.update(newUser);
        // 删除缓存
        redisService.remove(Constants.USER_INFO_KEY + email);
        log.info("用户：{}，头像更新成功！", email);
        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(true)
                .build();
    }

    @Override
    public Response<Boolean> updateUserInfo(String nickname, String biography, String token) {
        if (isEmpty(nickname) && isEmpty(biography)) {
            log.error("更新用户信息失败，参数错误: {}", Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false).build();
        }
        if (nickname.length() < 5 || nickname.length() > 25) {
            log.error("昵称长度错误: {}", Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo());
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false).build();
        }

        // 获取邮箱
        String email = "";
        try {
            email = jwtUtil.getEmailFromToken(token);
        } catch (Exception e) {
            log.error("获取用户邮箱失败: {}", Constants.ErrorCode.UN_ERROR.getInfo(), e);
            throw new AppException(
                    Constants.ErrorCode.UN_ERROR.getCode(),
                    Constants.ErrorCode.UN_ERROR.getInfo(), e);
        }
        Users user = usersDao.findByEmail(email);
        if (user == null) {
            log.error("用户不存在: {}", email);
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                    .data(false).build();
        }
        // 判断是否和以前相同
        if (nickname.equals(user.getNickname()) && biography.equals(user.getBiography())) {
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.SUCCESS.getCode())
                    .info(Constants.ErrorCode.SUCCESS.getInfo())
                    .data(true).build();
        }
        Users newUser = new Users();
        newUser.setEmail(email);
        if (!isEmpty(nickname)) {newUser.setNickname(nickname);}
        if (!isEmpty(biography)) {newUser.setBiography(biography);}
        // 更新用户信息
        usersDao.update(newUser);
        // 删除 Redis 的信息
        redisService.remove(Constants.USER_INFO_KEY + email);
        log.info("用户：{}，更新信息成功！", email);
        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(true).build();
    }

    @Override
    public Response<List<UsersDTO>> getUserList(String token) {
        // 获取用户权限
        String role = jwtUtil.getRoleFromToken(token);
        if (!role.equals(UserRoleVO.ADMIN.getCode()) && !role.equals(UserRoleVO.DECISION_MAKER.getCode())) {
            log.error("获取用户列表失败，权限错误: {}", Constants.ErrorCode.UNAUTHORIZED.getInfo());
            return Response.<List<UsersDTO>>builder()
                    .code(Constants.ErrorCode.UNAUTHORIZED.getCode())
                    .info(Constants.ErrorCode.UNAUTHORIZED.getInfo())
                    .data(Collections.emptyList())
                    .build();
        }
        List<Users> userList = usersDao.findUserList();
        if (null == userList || userList.isEmpty()) {
            return Response.<List<UsersDTO>>builder()
                    .code(Constants.ErrorCode.SUCCESS.getCode())
                    .info(Constants.ErrorCode.SUCCESS.getInfo())
                    .data(Collections.emptyList())
                    .build();
        }
        // 转为DTO类型
        List<UsersDTO> usersDTOS = userList.stream()
                .map(user -> UsersDTO.builder()
                        .id(user.getId())
                        .email(user.getEmail())
                        .nickname(user.getNickname())
                        .avatarUrl(user.getAvatarUrl())
                        .biography(user.getBiography())
                        .userStatus(user.getUserStatus())
                        .userRole(user.getUserRole())
                        .build())
                .collect(Collectors.toList());
        log.info("获取用户列表成功！");
        return Response.<List<UsersDTO>>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(usersDTOS)
                .build();
    }

    @Override
    public Response<Boolean> editUser(String email, String status, String role, String token) {
        // 获取请求者角色
        String roleFromToken = jwtUtil.getRoleFromToken(token);
        String adminRole = UserRoleVO.ADMIN.getCode();
        String decisionMakerRole = UserRoleVO.DECISION_MAKER.getCode();
        // 1. 权限校验：只有管理员或决策者可以操作
        if (!roleFromToken.equals(adminRole) && !roleFromToken.equals(decisionMakerRole)) {
            log.error("编辑用户失败，权限错误: {}", Constants.ErrorCode.UNAUTHORIZED.getInfo());
            return buildErrorResponse(Constants.ErrorCode.UNAUTHORIZED);
        }
        // 2. 参数非空校验
        if (isEmpty(email) || isEmpty(status) || isEmpty(role)) {
            log.error("编辑用户失败，参数错误: {}", Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo());
            return buildErrorResponse(Constants.ErrorCode.ILLEGAL_PARAMETER);
        }
        // 3. 校验被修改用户是否存在
        Users isExistUser = usersDao.findByEmail(email);
        if (isExistUser == null) {
            log.error("编辑用户失败，用户不存在: {}", Constants.ErrorCode.USER_NOT_EXIST.getInfo());
            return buildErrorResponse(Constants.ErrorCode.USER_NOT_EXIST);
        }
        // 4. 根据请求者角色进行细粒度权限控制
        if (roleFromToken.equals(adminRole)) {
            // 管理员只能修改普通用户（非管理员、非决策者）
            if (isExistUser.getUserRole().equals(adminRole) ||
                    isExistUser.getUserRole().equals(decisionMakerRole)) {
                log.error("管理员无法修改管理员或决策者");
                return buildErrorResponse(Constants.ErrorCode.UNAUTHORIZED);
            }
        } else {
            // 决策者不能修改任何决策者（包括自己）
            if (isExistUser.getUserRole().equals(decisionMakerRole)) {
                log.error("决策者无法修改其他决策者");
                return buildErrorResponseWithMessage("无法修改决策者用户");
            }
            // 决策者禁止将用户角色设置为决策者
            if (role.equals(decisionMakerRole)) {
                log.error("禁止设置决策者角色");
                return buildErrorResponseWithMessage("无法分配决策者角色");
            }
        }
        // 5. 执行更新操作
        try {
            Users users = Users.builder()
                    .email(email)
                    .userStatus(status)
                    .userRole(role).build();
            usersDao.update(users);
        } catch (Exception e) {
            log.error("编辑用户失败: {}", e.getMessage(), e);
            return buildErrorResponse(Constants.ErrorCode.UN_ERROR);
        }
        log.info("编辑用户成功，用户：{}", email);
        return buildSuccessResponse();
    }

    // 辅助方法：构建错误响应
    private Response<Boolean> buildErrorResponse(Constants.ErrorCode errorCode) {
        return Response.<Boolean>builder()
                .code(errorCode.getCode())
                .info(errorCode.getInfo())
                .data(false)
                .build();
    }

    // 辅助方法：构建带自定义信息的错误响应
    private Response<Boolean> buildErrorResponseWithMessage(String message) {
        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.UNAUTHORIZED.getCode())
                .info(message)
                .data(false)
                .build();
    }

    // 辅助方法：构建成功响应
    private Response<Boolean> buildSuccessResponse() {
        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info(Constants.ErrorCode.SUCCESS.getInfo())
                .data(true)
                .build();
    }

    @Override
    public Response<Boolean> resetPassword(String email, String token) {
        // 获取当前用户信息
        String currentRole = jwtUtil.getRoleFromToken(token);
        String currentEmail = jwtUtil.getEmailFromToken(token);

        // 1. 验证操作者身份
        if (!UserRoleVO.ADMIN.getCode().equals(currentRole)
                && !UserRoleVO.DECISION_MAKER.getCode().equals(currentRole)) {
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.UNAUTHORIZED.getCode())
                    .info("仅管理员和决策者可执行此操作")
                    .data(false)
                    .build();
        }

        // 2. 参数校验
        if (isEmpty(email)) {
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.ILLEGAL_PARAMETER.getCode())
                    .info(Constants.ErrorCode.ILLEGAL_PARAMETER.getInfo())
                    .data(false)
                    .build();
        }

        // 3. 防止自我密码重置
        if (email.equals(currentEmail)) {
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.UNAUTHORIZED.getCode())
                    .info("请前往头像区域修改个人密码")
                    .data(false)
                    .build();
        }

        // 4. 获取目标用户信息
        Users targetUser = usersDao.findByEmail(email);
        if (targetUser == null) {
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.USER_NOT_EXIST.getCode())
                    .info(Constants.ErrorCode.USER_NOT_EXIST.getInfo())
                    .data(false)
                    .build();
        }

        // 5. 权限验证
        String targetRole = targetUser.getUserRole();
        if (UserRoleVO.DECISION_MAKER.getCode().equals(currentRole)) {
            // 决策者只能操作管理员和普通用户
            if (!UserRoleVO.ADMIN.getCode().equals(targetRole)
                    && !UserRoleVO.USER.getCode().equals(targetRole)) {
                return Response.<Boolean>builder()
                        .code(Constants.ErrorCode.UNAUTHORIZED.getCode())
                        .info(Constants.ErrorCode.UNAUTHORIZED.getInfo())
                        .data(false)
                        .build();
            }
        } else if (UserRoleVO.ADMIN.getCode().equals(currentRole)) {
            // 管理员只能操作普通用户
            if (!UserRoleVO.USER.getCode().equals(targetRole)) {
                return Response.<Boolean>builder()
                        .code(Constants.ErrorCode.UNAUTHORIZED.getCode())
                        .info(Constants.ErrorCode.UNAUTHORIZED.getInfo())
                        .data(false)
                        .build();
            }
        }

        // 6. 执行密码重置
        try {
            String encryptedPwd = aesUtil.encrypt(Constants.DEFAULT_PASSWORD);
            usersDao.resetPassword(Users.builder()
                    .email(email)
                    .password(encryptedPwd)
                    .build());
        } catch (Exception e) {
            log.error("密码重置失败: {}", e.getMessage(), e);
            return Response.<Boolean>builder()
                    .code(Constants.ErrorCode.UN_ERROR.getCode())
                    .info("系统异常，请稍后重试")
                    .data(false)
                    .build();
        }

        return Response.<Boolean>builder()
                .code(Constants.ErrorCode.SUCCESS.getCode())
                .info("密码重置成功")
                .data(true)
                .build();
    }

    /**
     * 检查字符串是否为空
     *
     * @param str 需要检查的字符串
     * @return 如果为空返回 true，否则返回 false
     */
    private boolean isEmpty(String str) {
        return !StringUtils.hasText(str);
    }

}
